#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"QMessageBox"
#include"QNetworkDatagram"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket=new QUdpSocket();
    connect(socket,&QUdpSocket::readyRead,this,&MainWindow::processRequest);
    bool ret= socket->bind(QHostAddress::Any,8888);
    if(!ret)
    {
        QMessageBox::critical(this,"服务器出错",socket->errorString());
    }

}

void MainWindow::processRequest()
{
    //接受数据包
    const QNetworkDatagram &recv = socket->receiveDatagram();
    QString request=recv.data();

    //处理信息
    QString response=process(request);
    QNetworkDatagram responseDatagram(response.toUtf8(), recv.senderAddress(), recv.senderPort());
    socket->writeDatagram(responseDatagram);
    // 把这次交互的信息, 显示到界面上.
    QString log = "[" + recv.senderAddress().toString() + ":" + QString::number(recv.senderPort())
            + "] req: " + request + ", resp: " + response;
    ui->listWidget->addItem(log);







}


QString MainWindow::process(QString s)
{
    return s;
}

MainWindow::~MainWindow()
{
    delete ui;
}

